<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="商品名" prop="productName">
        <el-input
          v-model="queryParams.productName"
          placeholder="请输入商品名"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        <el-button
          type="primary"
          @click="handleAdd"
          v-hasPermi="['manage:product:add']"
        >新增数据</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5"></el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" align="center" prop="id" />
      <el-table-column label="商品名" align="center" prop="productName" />
      <el-table-column label="商品图片" align="center" prop="productImagePath" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.productImagePath" :width="50" :height="50"/>
        </template>
      </el-table-column>
      <el-table-column label="商品类型" align="center" prop="productType">
        <template #default="scope">
          <dict-tag :options="product_type" :value="scope.row.productType"/>
        </template>
      </el-table-column>
      <el-table-column label="商品状态" align="center">
        <template #default="scope">
          <span v-if="scope.row.productQuantity > 0">有货</span>
          <span v-else>无货</span>
        </template>
      </el-table-column>
      <el-table-column label="商品数量" align="center" prop="productQuantity" />
      <el-table-column label="修改时间" align="center" prop="updatedAt" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.updatedAt, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" @click="handleUpdate(scope.row)" v-hasPermi="['manage:product:edit']">修改</el-button>
          <el-button link type="primary" @click="handleDelete(scope.row)" v-hasPermi="['manage:product:remove']">删除</el-button>
          <el-button link type="primary" @click="handleStock(scope.row)" v-hasPermi="['manage:product:stock']">出入库</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改仓库出入库管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="productRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="商品名" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入商品名" />
        </el-form-item>
        <el-form-item label="商品图片" prop="productImagePath">
          <image-upload v-model="form.productImagePath"/>
        </el-form-item>
        <el-form-item label="商品类型" prop="productType">
          <el-select v-model="form.productType" placeholder="请选择商品类型">
            <el-option
              v-for="dict in product_type"
              :key="dict.value"
              :label="dict.label"
              :value="parseInt(dict.value)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品数量" prop="productQuantity">
          <el-input v-model="form.productQuantity" placeholder="请输入商品数量" />
        </el-form-item>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 出入库对话框 -->
    <el-dialog title="商品出入库" v-model="stockDialogOpen" width="400px" append-to-body>
      <el-form ref="stockRef" :model="stockForm" :rules="stockRules" label-width="80px">
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="stockForm.type">
            <el-radio :label="'in'">入库</el-radio>
            <el-radio :label="'out'">出库</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="数量" prop="quantity">
          <el-input-number v-model="stockForm.quantity" :min="0" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitStock">确 定</el-button>
          <el-button @click="closeStockDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Product">
import { listProduct, getProduct, delProduct, addProduct, updateProduct, stockProduct } from "@/api/manage/product";
import { getCurrentInstance } from 'vue';
import { ref, reactive, toRefs } from 'vue';

const { proxy } = getCurrentInstance();
const { product_type, product_status } = proxy.useDict('product_type', 'product_status');

const productList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const stockDialogOpen = ref(false);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    productName: null,
  },
  rules: {
    productName: [
      { required: true, message: "商品名不能为空", trigger: "blur" }
    ],
    productImagePath: [
      { required: true, message: "商品图片路径不能为空", trigger: "blur" }
    ],
    productType: [
      { required: true, message: "商品类型不能为空", trigger: "change" }
    ],
    productQuantity: [
      { required: true, message: "商品数量不能为空", trigger: "blur" }
    ]
  },
  stockForm: {
    id: null,
    type: null,
    quantity: null
  },
  stockRules: {
    type: [
      { required: true, message: "出入库类型不能为空", trigger: "change" }
    ],
    quantity: [
      { required: true, message: "出入库数量不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules, stockForm, stockRules } = toRefs(data);

/** 查询仓库出入库管理列表 */
function getList() {
  loading.value = true;
  listProduct(queryParams.value).then(response => {
    productList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    productName: null,
    productImagePath: null,
    productType: null,
    productStatus: null,
    productQuantity: null,
    createdAt: null,
    updatedAt: null,
    createdBy: null,
    updatedBy: null,
    remarks: null
  };
  proxy.resetForm("productRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加仓库出入库管理";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value;
  getProduct(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改仓库出入库管理";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["productRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        // 更新商品
        updateProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        // 新增商品
        addProduct(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除仓库出入库管理编号为"' + _ids + '"的数据项？').then(function() {
    return delProduct(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('manage/product/export', {
    ...queryParams.value
  }, `product_${new Date().getTime()}.xlsx`)
}

/** 出入库按钮操作 */
function handleStock(row) {
  stockForm.value = {
    id: row.id,
    type: null,
    quantity: null
  };
  stockDialogOpen.value = true;
}

/** 提交出入库操作 */
function submitStock() {
  proxy.$refs["stockRef"].validate(valid => {
    if (valid) {
      stockProduct(stockForm.value).then(response => {
        proxy.$modal.msgSuccess(`商品${stockForm.value.type === 'in' ? '入库' : '出库'}成功`);
        stockDialogOpen.value = false;
        getList(); // 更新商品信息后重新获取列表
      }).catch(error => {
        proxy.$modal.msgError(`商品${stockForm.value.type === 'in' ? '入库' : '出库'}失败: ${error.message}`);
      });
    }
  });
}

/** 关闭出入库对话框 */
function closeStockDialog() {
  stockDialogOpen.value = false;
  resetStockForm();
}

/** 重置出入库表单 */
function resetStockForm() {
  stockForm.value = {
    id: null,
    type: null,
    quantity: null
  };
  proxy.resetForm("stockRef");
}

getList();
</script>